<?php

namespace app\admin\model\user;

use app\common\model\TimeModel;
use think\facade\Db;

class ScoreLog extends TimeModel
{

    protected $name = "user_score_log";

    protected $deleteTime = false;
    //记录类型。你有新的类型，请添加到这里
    public static $types = [
        '1' => '签到赠送积分',
        '2' => '注册送积分',
        '3' => '管理员操作'
    ];
    /** 
     * @Author: Bryant  
     * @Date: 2023-06-14 16:42:14 
     * @method post 
     * @title 积分变动 
     */
    public static function changeScore($user_id, $before_score, $score, $type = 1, $remark = '', $ordeNo = '')
    {
        if(empty($before_score)){
            $before_score = Db::name('user_assets')->where('user_id',$user_id)->value('score');
        }
        // 启动事务
        Db::startTrans();
        try {
            $after_score = bcadd($before_score, $score, 2);
            //如果变动结果小于0 则返回失败
            if ($after_score < 0) {
                exception('积分不足');
            }
            if ($after_score == $before_score) {
                exception('积分没有发生变化');
            }
            $ret = Db::name('user_assets')->where('user_id', $user_id)->update([
                'score' => $after_score,
            ]);
            if (!$ret) {
                exception('更新会员积分失败');
            }

            $data = array(
                'user_id' => $user_id,
                'change_score' => $score,
                'before_score' => $before_score,
                'after_score' => $after_score,
                'change_type' => $type,
                'remark' => $remark,
                'order_sn' => $ordeNo,
                'create_time' => time()
            );
            $result = Db::name('user_score_log')->insert($data);
            if (!$result) {
                exception('插入积分记录失败');
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
        return true;
    }
}